package com.onpositive.page.pagerendering;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import com.onpositive.page.core.NamedLink;

public class MenuRenderer {

	NamedLink[] generalLinks;
	NamedLink[] specialLinks = new NamedLink[]{new NamedLink("/commit.commit","Upload"),new NamedLink("/reslist.page","Resources"),new NamedLink("/profile.page","User Profile")};

	public static final String SPECMARK = "special";
	public static final String GENMARK = "general";

	public MenuRenderer(InputStream stream) throws IOException {
		InputStreamReader r = new InputStreamReader(stream);
		BufferedReader reader = new BufferedReader(r);
		ArrayList<NamedLink> gLinks = new ArrayList<NamedLink>();
		ArrayList<NamedLink> sLinks = new ArrayList<NamedLink>();
		while (true) {
			String readLine = reader.readLine();
			if (readLine == null) {
				break;
			}
			readLine = readLine.trim();
			if (readLine.length() > 0) {
				String[] splitted = readLine.split("#");
				if(splitted.length > 1){
				String url = splitted[0];
				String title = splitted[1];
				gLinks.add(new NamedLink(url, title));
				}
				/*String kind = splitted[2];
				if (kind.equals(GENMARK)) {
					gLinks.add(new NamedLink(url, title));
				} else if (kind.equals(SPECMARK)) {
					sLinks.add(new NamedLink(url, title));
				}*/
			}
		}
		this.generalLinks = gLinks.toArray(new NamedLink[gLinks.size()]);
		//this.specialLinks = sLinks.toArray(new NamedLink[sLinks.size()]);
	}

	public String menu(String url, boolean showSpecial) {
		StringBuilder bld = new StringBuilder();
		bld.append("<ul>\r\n");
		bld.append("</ul>");

		for (NamedLink l : generalLinks) {
			if (isSelected(l, url)) {
				bld.append("<li class=\"selected\">");
			} else {
				bld.append("<li>");
			}
			bld.append("<a href=\"" + l.getUrl() + "\">" + l.getTitle()
					+ "</a>");
			bld.append("</li>");
			bld.append("</ul>");
		}

		if (showSpecial) {
			for (NamedLink l : specialLinks) {
				if (isSelected(l, url)) {
					bld.append("<li class=\"selected\">");
				} else {
					bld.append("<li>");
				}
				bld.append("<a href=\"" + l.getUrl() + "\">" + l.getTitle()
						+ "</a>");
				bld.append("</li>");
				bld.append("</ul>");
			}
		}
		return bld.toString();
	}

	private boolean isSelected(NamedLink l, String url) {
		return l.getUrl().equals(url);
	}
}
